<template>
  <div class="app-container">
    <div class="search_container_warp">
      <el-form
        ref="queryFormRef"
        class="search_container"
        :model="queryParams"
        :inline="true"
      >
        <el-form-item label="赛项名称" prop="matchCode">
          <el-select
            v-model="queryParams.matchCode"
            @change="searchChangeFn"
            style="width: 360px"
          >
            <el-option
              v-for="item in eventDataList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="组别" prop="matchGroup">
          <el-select
            style="width: 120px"
            clearable
            v-model="queryParams.matchGroup"
            @change="matchGroupChange"
          >
            <el-option
              v-for="item in queryGroupOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="schoolName" label="学校/姓名">
          <el-input
						style="width: 140px"
            v-model="queryParams.schoolName"
            clearable
            @keyup.enter="handleQuery"
          >
            <template #suffix>
              <el-icon
                class="el-input__icon searchIconClass"
                @click="handleQuery"
                ><search
              /></el-icon>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <div class="card-header">
          <ul class="card_right_btn_Wrap"></ul>
          <ul class="card_right_btn_Wrap">
            <li>
              <el-button type="primary" @click="openDialog()"> 新增</el-button>
            </li>
            <li>
              <Custom-Upload
                @set-file="teamUploadFn"
                :showFileFlag="false"
                btnName="导入"
                fileType="xlsx"
              />
            </li>
            <li>
              <el-button type="primary" @click="downloadTemplateFn">
                下载模版
              </el-button>
            </li>
          </ul>
        </div>
      </template>

      <el-table
        ref="dataTableRef"
        class="customTableClass"
        v-loading="loading"
        :data="dataList"
        highlight-current-row
        border
      >
        <el-table-column 
					label="序号" 
					type="index" 
					align="center" 
					width="60" 
				/>
        <el-table-column
          label="学校名称"
          sortable
          prop="schoolName"
          min-width="140"
        />
        <el-table-column
          label="组别"
          sortable
          prop="matchGroupName"
          align="center"
          width="90"
        />
        <el-table-column
          label="赛队编码"          
          prop="teamNumber"
          align="center"
          width="85"
        />
        <el-table-column
          label="姓名"
          prop="stuName"
          align="center"
          width="100"
        />
        <el-table-column
          label="身份证号码"
          prop="stuIdCard"
          align="center"
          width="180"
        />
        <el-table-column
          label="手机号码"
          prop="stuPhone"
          align="center"
          width="115"
        />
        <el-table-column
          label="带队老师"
          prop="teacherName"
          align="center"
          width="90"
        />
				<!--
        <el-table-column
          label="老师手机"
          prop="teacherPhone"
          align="center"
          width="115"
        /> 
				-->
        <el-table-column label="操作" prop="code" align="center" width="80">
          <template #default="scope">
            <el-icon :size="16" class="editIconClass">
              <Edit @click="editFn(scope.row)" />
            </el-icon>
            <el-icon :size="16" class="deleteIconClass">
              <i-ep-delete @click="handleDelete(scope.row.id)" />
            </el-icon>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 修改状态弹窗 -->
    <el-dialog
      v-if="dialog.visible"
      modal-class="maxHeightClass"
      v-model="dialog.visible"
      :title="dialog.title"
      width="600px"
      draggable
      align-center
      @close="closeDialog"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="赛项名称" prop="matchCode">
          <el-select v-model="formData.matchCode" @change="changeFn">
            <el-option
              v-for="item in eventDataList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="组别" prop="matchGroup">
          <el-select v-model="formData.matchGroup" @change="matchGroupChangeFn">
            <el-option
              v-for="item in matchGroupOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="学校名称" prop="schoolName">
          <el-input v-model="formData.schoolName" placeholder="" />
        </el-form-item>
        <el-form-item label="参赛人姓名" prop="stuName">
          <el-input v-model="formData.stuName" placeholder="" />
        </el-form-item>
				<el-form-item label="身份证号" prop="stuIdCard">
				  <el-input v-model="formData.stuIdCard" placeholder="" />
				</el-form-item>
        <el-form-item label="赛队编码" prop="teamNumber">
          <el-input
            v-model="formData.teamNumber"
            placeholder=""
            maxlength="10"
          />
        </el-form-item>        
        <el-form-item label="手机号码" prop="stuPhone">
          <el-input v-model="formData.stuPhone" placeholder="" />
        </el-form-item>
        <el-form-item label="带队老师" prop="teacherName">
          <el-input v-model="formData.teacherName" placeholder="" />
        </el-form-item>
        <el-form-item label="老师手机" prop="teacherPhone">
          <el-input v-model="formData.teacherPhone" placeholder="" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { getEventList } from "@/api/examManagement";
import {
  getTeamList,
  teamCreate,
  teamUpdate,
  teamDelete,
  downloadTemplate,
  teamUpload,
} from "@/api/teamManagement";
import { getDictionaryPage } from "@/api/examManagement";
import { ItemPageVO, Options } from "@/api/teamManagement/types";
import {
  queryFilter,
  moreQueryFilter,
  computeHeiht,
  validateIdCard,
} from "@/utils/index";

defineOptions({
  name: "TeamManagement",
  inheritAttrs: false,
});

const queryFormRef = ref(ElForm);
const formRef = ref(ElForm);

const groupOptions = ref<Options[]>([]);
const queryGroupOptions = ref<Options[]>([]);
const matchGroupOptions = ref<any[]>([]);
const eventDataList = ref<any[]>([]);

const loading = ref(false);

const dataList = ref<ItemPageVO[]>([]);
const originaldataList = ref<ItemPageVO[]>([]);

const queryParams = reactive<ItemPageVO>({});

const dialog = reactive({
  title: "修改状态",
  visible: false,
});
const formData = reactive<ItemPageVO>({});

const checkstuIdCard = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error("Please input the age"));
  }
  if (!validateIdCard(value)) {
    callback(new Error(" "));
  } else {
    callback();
  }
};

// const checkstuPhone = (rule: any, value: any, callback: any) => {
//   if (!value) {
//     return callback(new Error("Please input the age"));
//   }
//   if (/^1[34578]\d{9}$/.test(value)) {
//     callback();
//   } else {
//     callback(new Error(" "));
//   }
// };
// const checkstuPhone2 = (rule: any, value: any, callback: any) => {
//   if (!value) {
//     callback();
//   }
//   if (/^1[34578]\d{9}$/.test(value)) {
//     callback();
//   } else {
//     callback(new Error(" "));
//   }
// };

const rules = reactive({
  matchCode: [{ required: true, message: " ", trigger: "change" }],
  matchGroup: [{ required: true, message: " ", trigger: "change" }],
  schoolName: [{ required: true, message: " ", trigger: "change" }],
  stuName: [{ required: true, message: " ", trigger: "change" }],
  teamNumber: [{ required: true, message: " ", trigger: "change" }],
  stuIdCard: [
    {
      validator: checkstuIdCard,
      required: true,
      message: " ",
      trigger: "blur",
    },
  ],
  // stuPhone: [
  //   {
  //     validator: checkstuPhone,
  //     required: false,
  //     message: " ",
  //     trigger: "blur",
  //   },
  // ],
  // teacherPhone: [
  //   {
  //     validator: checkstuPhone2,
  //     message: " ",
  //     trigger: "blur",
  //   },
  // ],
});

/** 查询 */
function handleQuery() {
  let { schoolName } = queryParams;
  let arr: Options[] = [
    { label: "stuName", value: schoolName || "" },
    { label: "schoolName", value: schoolName || "" },
  ];

  if (schoolName) {
    dataList.value = moreQueryFilter(originaldataList.value, arr);
  } else {
    query();
  }
}

/** 接口查询 */
function query() {
  loading.value = true;
  getTeamList({
    matchGroup: queryParams.matchGroup,
    matchId: queryParams.matchId,
  })
    .then(({ data }) => {
      const list = data.map((item: any) => {
        item.matchId += ""; // 统一格式 字符串
        item.matchGroup += "";
        item.matchGroupName = groupOptions.value.find(
          (v) => v.value === item.matchGroup
        )?.label;
        return {
          ...item,
        };
      });
      dataList.value = list;
      originaldataList.value = list;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  query();
}

/** 关闭表单弹窗 */
function closeDialog() {
  dialog.visible = false;
  formRef.value.resetFields();
}
/** 跳转页面 */
function openDialog(id?: any) {
  dialog.visible = true;
  dialog.title = "新增赛队";
  formData.matchId = "";
  formData.matchCode = "";
  formData.stuName = "";
  formData.matchGroup = "";
  formData.schoolName = "";
  formData.teamNumber = "";
  formData.stuIdCard = "";
  formData.stuPhone = "";
  formData.teacherName = "";
  formData.teacherPhone = "";
}
/** open表单弹窗 */
function editFn(data: ItemPageVO) {
  dialog.visible = true;
  dialog.title = "修改赛队";
  const {
    matchId,
    stuName,
    schoolName,
    teamNumber,
    stuIdCard,
    stuPhone,
    teacherName,
    teacherPhone,
    matchGroup,
    id,
    matchCode,
  } = data;
  // formData.value = data.value
  formData.matchId = matchId;
  formData.stuName = stuName;
  formData.matchGroup = matchGroup;
  formData.schoolName = schoolName;
  formData.teamNumber = teamNumber;
  formData.stuIdCard = stuIdCard;
  formData.stuPhone = stuPhone;
  formData.teacherName = teacherName;
  formData.teacherPhone = teacherPhone;
  formData.id = id;
  formData.matchCode = matchCode;
  changeFn(matchCode, false);
}
/** 提交表单 */
function handleSubmit() {
  // closeDialog();
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      if (formData.id) {
        teamUpdate(formData).then((res) => {
          ElMessage.success("修改成功");
          dialog.visible = false;
          query();
        });
      } else {
        teamCreate(formData).then((res) => {
          ElMessage.success("新增成功");
          dialog.visible = false;
          query();
        });
      }
    }
  });
}

/** 删除赛队人员 */
function handleDelete(id?: any) {
  ElMessageBox.confirm("确认删除数据项?", "确认删除", {
    confirmButtonText: "确 定",
    cancelButtonText: "取 消",
    type: "error",
  }).then(() => {
    loading.value = true;
    teamDelete(id)
      .then(() => {
        ElMessage.success("删除成功");
        resetQuery();
      })
      .finally(() => (loading.value = false));
  });
}

function teamUploadFn(data: any) {
  let params = new FormData();
  // params.append("id", queryParams.paperId);
  params.append("file", data);

  loading.value = true;
  teamUpload(params)
    .then((res) => {
      ElMessage.success("导入成功");
    })
    .finally(() => {
      loading.value = false;
      resetQuery();
    });
}
function downloadTemplateFn() {
  downloadTemplate().then((res) => {
    const blob = new Blob([res.data], { type: "text/plain" });
    const url = URL.createObjectURL(blob);
    const downloadLink = document.createElement("a");
    downloadLink.href = url;
    downloadLink.download = "teams_import_template.xlsx";
    downloadLink.click();
  });
}
// 搜索选择赛项名称
function searchChangeFn(value: any) {
  queryParams.matchCode = value;
  changeFn(value, true);
}

// 选择赛项名称
function changeFn(value: any, type: boolean | undefined) {
  let list: any = [];
  eventDataList.value.forEach((v) => {
    if (v.value === value) {
      // 过滤事项对应的组别
      list = v.matchGroupList.map((j: any) => {
        const { matchGroup, matchId } = j;
        // matchId // 赛项ID
        let item = {
          value: matchGroup + "",
          label: matchGroup,
          matchId: matchId,
        };
        // 组装组别的key value
        groupOptions.value.forEach((k) => {
          if (matchGroup === k.value) {
            item.label = k.label;
          }
        });
        return item;
      });
    }
  });
  if (!type) {
    matchGroupOptions.value = [...list];
    // 默认选择第一个组别
    if (matchGroupOptions.value?.length) {
      formData.matchGroup = matchGroupOptions.value[0].value;
      formData.matchId = matchGroupOptions.value[0].matchId;
    }
  } else {
    queryGroupOptions.value = [...list];
    // 默认选择第一个组别
    if (queryGroupOptions.value?.length) {
      queryParams.matchGroup = queryGroupOptions.value[0].value;
      queryParams.matchId = queryGroupOptions.value[0]?.matchId;
      matchGroupChange(queryParams.matchGroup);
    }
  }
}

// 选择组别
function matchGroupChange(value: any) {
  queryParams.matchGroup = value;
  queryGroupOptions.value.forEach((v: any) => {
    if (value === v.value) {
      queryParams.matchId = v.matchId;
    }
  });
  query();
}

// 选择组别
function matchGroupChangeFn(value: any) {
  matchGroupOptions.value.forEach((v) => {
    if (value === v.value) {
      formData.matchId = v.matchId;
      query();
    }
  });
}

onMounted(async () => {
  loading.value = true;
  // 获取组别
  let { data } = await getDictionaryPage("MATCH_GROUP", 1);
  groupOptions.value = data.map((v: any) => {
    return {
      label: v.name,
      value: v.myKey,
    };
  });

  // 获取事项
  await getEventList()
    .then(({ data }) => {
      let codeList = new Map();
      let listData = data.map((item: any) => {
        item.matchGroup += ""; // 统一格式 字符串
        item.value = item.matchCode;
        item.label = item.matchName;
        // 把赛项下的组别收集起来
        if (!codeList.has(item.matchCode)) {
          codeList.set(item.matchCode, [
            { matchGroup: item.matchGroup, matchId: item.id },
          ]);
        } else {
          let list = codeList.get(item.matchCode);
          list.splice(list.length, 0, {
            matchGroup: item.matchGroup,
            matchId: item.id,
          });

          codeList.set(item.matchCode, list);
        }
        return item;
      });
      // 把赛项下的组别赋值
      listData.forEach((item: any) => {
        if (codeList.has(item.matchCode)) {
          item.matchGroupList = codeList.get(item.matchCode);
        }
      });
      // 过滤重复赛项
      let resultList = new Map();
      listData.forEach((v: any) => {
        if (!resultList.has(v.matchCode)) {
          resultList.set(v.matchCode, v);
        }
      });

      // eventDataList.value = [...listData];
      eventDataList.value = [...resultList.values()];
      searchChangeFn(eventDataList.value[0].value);
    })
    .finally(() => {
      loading.value = false;
    });
  // query();
  computeHeiht(170);
});
</script>
<style lang="scss" scoped>
.search_right_btn_Wrap {
  float: right;
  display: block;
  margin: 8px 10px 0 0;
  li {
    float: left;
    margin-left: 10px;
  }
  .el-select {
    width: 180px;
  }
}

.el-form--inline .el-form-item {
  margin-right: 10px;
}
.el-dialog {
  min-height: 580px;
}
</style>
